package com.zhss.concurrency.guarded;

import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName GuardedQueue
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/9/1 15:53
 * @Version 1.0
 */
public class GuardedQueue {
	private final Queue<Integer> source;

	public GuardedQueue() {
		source = new LinkedBlockingQueue<>();
	}

	public synchronized void put(Integer val) {
		source.add(val);
		notifyAll();
	}

	public synchronized Integer get() throws InterruptedException {
		while (source.isEmpty()) {
			wait();
		}
		return source.peek();
	}

	public static void main(String[] args) throws InterruptedException {
		GuardedQueue guardedQueue = new GuardedQueue();
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		executorService.execute(()->{
			try {
				System.out.println(Thread.currentThread().getName() + "等待获取值");
				Integer integer = guardedQueue.get();
				System.out.println(Thread.currentThread().getName() + " 获取到值: " + integer);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		Thread.sleep(2000L);
		executorService.execute(()->{
			guardedQueue.put(1);
		});
		executorService.shutdown();
		executorService.awaitTermination(20, TimeUnit.SECONDS);
	}
}
